
//=========================================================================
// Copyright (C) 2025 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

// g++ example.cpp ../tlsf/tlsf.c ../tlsf/TlsfStdString.cpp

#include<iostream>
#include "../tlsf/TlsfStdString.h"

constexpr size_t memory_size = 1024 * 1024; //1MB;
uint8_t memory_area[memory_size];
uint8_t memory_area_backup[memory_size];
uint8_t memory_area_safe[memory_size];
como::MemoryHolder* Current_MH = nullptr;

void warning(void)
{
    std::cerr << "main memory area cant allocate\n";
    std::cerr << "use upstream memory area\n";
}

void* get_safe_memory()
{
    return memory_area_safe;
}

void on_memory_failure()
{
    static como::MemoryHolder MH_Safe = como::MemoryHolder(memory_size, memory_area_safe);

    MH_Safe = como::MemoryHolder(memory_size, get_safe_memory());
    Current_MH = &MH_Safe;
}

int main()
{
    como::MemoryHolder MH1(memory_size, memory_area, nullptr, 100);
    como::MemoryHolder MH2(memory_size, memory_area_backup);

    MH1.Set_Upstream(&MH2);
    MH2.Set_OnFailture(warning);
    Current_MH = &MH1;

    como::TlsfString str(Current_MH);
}
/*
代码解析：
上述代码声明了两个MemoryHolder，MH1为主内存池，MH2为备用内存池
将MH2设置为MH1的上游内存池，这样当MH1分配失败时会自动调用MH2来分配内存
为MH2设置了在分配时使用的函数，这样当使用MH2进行分配时会调用warning函数来报警
使用Current_MH指针来指向MH1
当发生内存失效时，改变Current_MH的值指向新的内存池，这样后声明的变量都会使用新的内存池
*/
